package com.connect.server.handler;

import java.io.IOException;
import java.nio.BufferUnderflowException;
import java.nio.ByteBuffer;
import java.nio.channels.ClosedChannelException;

import org.xsocket.MaxReadSizeExceededException;
import org.xsocket.connection.IConnectHandler;
import org.xsocket.connection.IDataHandler;
import org.xsocket.connection.IDisconnectHandler;
import org.xsocket.connection.INonBlockingConnection;

import com.connect.agreement.Packet;
import com.game.manager.CommManager;
import com.module.login.LoginManager;
import com.server.ServerSimulation;
import com.server.User;

/**
 * 世界服务器的消息处理入口
 * @author chzcb
 * @email chzcb2008@gmail.com
 * @date 2011-8-31
 *
 */
public class WorldDataHandler implements IDataHandler, IConnectHandler, IDisconnectHandler {
    private char mark;
    private int size;
    private char crc;
    private byte group;
    private byte cmd;
    private ByteBuffer content;
    private char end;
    public boolean onData(INonBlockingConnection nbc) throws IOException, BufferUnderflowException, ClosedChannelException, MaxReadSizeExceededException {
        try {
        	while(nbc.available()>0){
        		mark = (char)nbc.readShort();
        		if(mark == 0x1234){
        			size = nbc.readInt();
        			crc = (char)nbc.readShort();
        			group = nbc.readByte();
        			cmd = nbc.readByte();
        			content = ByteBuffer.allocate((int)size);
        			ByteBuffer[] temp = nbc.readByteBufferByLength((int)size);
        			for(ByteBuffer b:temp){
        				if(b.position()>0)
        					b.flip();
        				content.put(b);
        			}
        			end = (char)nbc.readShort();
        			if(end == 0x4321){
        				Packet packet = new Packet();
        				packet.setBuffer(group, cmd, content);
        				if(packet.getCrc() == crc){
        					CommManager.get().update(nbc, packet);
        				}
        				else
        				{
        					System.out.println("CRC错误");
        				}
        			}
        			else
        			{
        				System.out.println("包结尾错误");
        			}
        		}
        		else
        		{
        			System.out.println("包头标识错误");
        		}
        	}
        } catch (Exception ex) {
            System.out.println("ReceiveDataException: " + ex.getMessage());
        }
        return true;
    }

    public boolean onConnect(INonBlockingConnection nbc) throws IOException, BufferUnderflowException, MaxReadSizeExceededException {
        try {
        	
        } catch (Exception ex) {
            System.out.println("onConnect: " + ex.getMessage());
        }
        return true;
    }

    public boolean onDisconnect(INonBlockingConnection nbc) throws IOException {
        try {
        	User user = ServerSimulation.get().onlineusers.get(nbc.getId());
        	ServerSimulation.get().detachUser(user,nbc);
        } catch (Exception ex) {
            System.out.println("onDisconnect: " + ex.getMessage());
        }
        return true;
    }


}